package me.project.android_service.util;

import me.project.common.exception.BusinessException;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class FileUploader {

    private static String url = "http://165.154.187.27:8087/file/upload";

    public static String upload(String filePath,String targetPath){
        try {
            URL uploadUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) uploadUrl.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);

            // 设置请求头部信息，必须为multipart/form-data
            String boundary = "Boundary-" + System.currentTimeMillis();
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

            try (OutputStream outputStream = connection.getOutputStream()) {
                // 上传文件
                File file = new File(filePath);
                String fileName = file.getName();
                writePart(outputStream, boundary, fileName, file);

                // 添加其他参数
                writePart(outputStream, boundary, "uploadPath", targetPath);

                // 结束请求体
                outputStream.write(("--" + boundary + "--\r\n").getBytes());
            }

            // 获取响应码
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            // 读取响应内容
            try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                System.out.println("Response Body: " + response.toString());
                String[] parts = response.toString().split(":\\s+");
                if (parts.length > 1) {
                    String fileId = parts[1]; // 取冒号后面的内容
                    System.out.println(fileId); // 输出或处理 fileId
                    return fileId;
                } else {
                    System.out.println("No colon found in the response or no content after the colon.");
                    return "failed";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("正在上传文件");
        }
    }

    private static void writePart(OutputStream outputStream, String boundary, String paramName, String paramValue) throws IOException {
        outputStream.write(("--" + boundary + "\r\n").getBytes());
        outputStream.write(("Content-Disposition: form-data; name=\"" + paramName + "\"\r\n\r\n").getBytes());
        outputStream.write((paramValue + "\r\n").getBytes());
    }

    private static void writePart(OutputStream outputStream, String boundary, String fileName, File file) throws IOException {
        outputStream.write(("--" + boundary + "\r\n").getBytes());
        outputStream.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"\r\n").getBytes());
        outputStream.write(("Content-Type: application/octet-stream\r\n\r\n").getBytes());

        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }

        outputStream.write("\r\n".getBytes());
    }

}
